package com.zl.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zl.service.WeixinService;
import com.zl.weixin.util.SignUtil;

/**   
* @Title: WeixinController.java 
* @Package com.zl.controller 
* @Description: 微信核心控制器
* @author chxl   
* @date 2015年8月5日 上午9:17:05 
* @version V1.0   
*/
@Controller
@RequestMapping("weixin")
@Scope("prototype")
public class WeixinController {
	@Autowired
	private WeixinService weixinService;
	
	@RequestMapping(method = RequestMethod.GET)
	public void get(HttpServletRequest request, HttpServletResponse response) {
		// 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
			out = null;
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public void post(HttpServletRequest request, HttpServletResponse response) {
		//暂时空着，在这里可处理用户请求SignUtil.java
		 try {  
	            request.setCharacterEncoding("UTF-8");  
	        } catch (UnsupportedEncodingException e) {  
	            e.printStackTrace();  
	        }  
	        // 调用核心业务类接收消息、处理消息  
	        String respMessage = weixinService.processRequest(request);  
	        // 响应消息  
	        PrintWriter out = null;  
	        try {  
	            out = response.getWriter();  
	            out.print(respMessage);  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } finally {  
	            out.close();  
	            out = null;  
	        }  
	}
}
